<template>
	<cmDialog v-model="dialogState" :modal-title="props.editId == '' ? '新增' : '编辑'" model-width="1200px">
		<el-tabs v-model="activeName" class="tabs" :before-leave="beforeTabLeave" @tab-change="handleTabClick">
			<el-tab-pane label="标准信息" name="tab1">
				<div class="box">
					<el-form
						ref="standardInfoRef"
						:model="standardInfo"
						:rules="props.projectId == '' ? standardInfoRules : standardInfoRules1"
						label-width="150px"
					>
						<el-row>
							<el-col :span="8">
								<el-form-item label="标准名称" prop="standardName">
									<el-input v-model="standardInfo.standardName" autocomplete="off" placeholder="请输入" :disabled="props.projectId != ''" />
								</el-form-item>
							</el-col>
							<el-col :span="8">
								<el-form-item label="英文名称" prop="standardEnName">
									<el-input v-model="standardInfo.standardEnName" autocomplete="off" placeholder="请输入" :disabled="props.isDisabled" />
								</el-form-item>
							</el-col>
							<el-col :span="8">
								<el-form-item label="标准编号" prop="standardNumber">
									<el-input v-model="standardInfo.standardNumber" autocomplete="off" placeholder="请输入" :disabled="props.projectId != ''" />
								</el-form-item>
							</el-col>
						</el-row>
						<el-row>
							<el-col :span="8">
								<el-form-item label="被替代标准名称" prop="substitutedName">
									<el-input v-model="standardInfo.substitutedName" autocomplete="off" placeholder="请输入" :disabled="props.isDisabled" />
								</el-form-item>
							</el-col>
							<el-col :span="8">
								<el-form-item label="备案号" prop="recordNumber">
									<el-input v-model="standardInfo.recordNumber" autocomplete="off" placeholder="请输入" :disabled="props.projectId != ''" />
								</el-form-item>
							</el-col>

							<el-col :span="8">
								<el-form-item label="被替代标准编号" prop="substitutedNo">
									<el-input v-model="standardInfo.substitutedNo" autocomplete="off" placeholder="请输入" :disabled="props.isDisabled" />
								</el-form-item>
							</el-col>
						</el-row>
						<el-row>
							<el-col :span="8">
								<el-form-item label="标准序号" prop="seqNo">
									<el-input v-model="standardInfo.seqNo" autocomplete="off" placeholder="请输入" :disabled="props.isDisabled" />
								</el-form-item>
							</el-col>
							<el-col :span="8">
								<el-form-item label="标准代次" prop="version">
									<el-input v-model="standardInfo.version" type="number" autocomplete="off" placeholder="请输入" :disabled="props.isDisabled" />
								</el-form-item>
							</el-col>
							<el-col :span="8">
								<el-form-item label="立项时间" prop="initiateTime">
									<el-date-picker
										v-model="standardInfo.initiateTime"
										type="date"
										format="YYYY-MM-DD"
										clearable
										value-format="YYYY-MM-DD"
										placeholder="请选择"
										:disabled="props.projectId != ''"
									/>
								</el-form-item>
							</el-col>
						</el-row>
						<el-row>
							<el-col :span="8">
								<el-form-item label="发布时间" prop="publishTime">
									<el-date-picker
										v-model="standardInfo.publishTime"
										type="date"
										format="YYYY-MM-DD"
										clearable
										value-format="YYYY-MM-DD"
										placeholder="请选择"
										:disabled="props.projectId != ''"
									/>
								</el-form-item>
							</el-col>
							<el-col :span="8">
								<el-form-item label="实施时间" prop="implementTime">
									<el-date-picker
										v-model="standardInfo.implementTime"
										type="date"
										format="YYYY-MM-DD"
										clearable
										value-format="YYYY-MM-DD"
										placeholder="请选择"
										:disabled="props.projectId != ''"
									/>
								</el-form-item>
							</el-col>
							<el-col :span="8">
								<el-form-item label="批准时间" prop="approvalTime">
									<el-date-picker
										v-model="standardInfo.approvalTime"
										type="date"
										format="YYYY-MM-DD"
										clearable
										value-format="YYYY-MM-DD"
										placeholder="请选择"
										:disabled="props.projectId != ''"
									/>
								</el-form-item>
							</el-col>
						</el-row>
						<el-row>
							<el-col :span="8">
								<el-form-item label="废止时间" prop="abolishTime">
									<el-date-picker
										v-model="standardInfo.abolishTime"
										type="date"
										format="YYYY-MM-DD"
										clearable
										value-format="YYYY-MM-DD"
										placeholder="请选择"
										:disabled="props.projectId != ''"
									/>
								</el-form-item>
							</el-col>
							<el-col :span="8">
								<el-form-item label="强制性分类">
									<el-select v-model="standardInfo.mandatoryCategoryVal" placeholder="请选择" clearable :disabled="props.isDisabled">
										<el-option v-for="item in mandatoryCategory.options" :key="item.id" :label="item.name" :value="item.id" />
									</el-select>
								</el-form-item>
							</el-col>
							<el-col :span="8">
								<el-form-item label="标准类别">
									<el-select v-model="standardInfo.standardCategoryVal" placeholder="请选择" clearable :disabled="props.isDisabled">
										<el-option v-for="item in standardCategory.options" :key="item.id" :label="item.name" :value="item.id" />
									</el-select>
								</el-form-item>
							</el-col>
						</el-row>
						<el-row>
							<el-col :span="8">
								<el-form-item label="标准状态">
									<el-select v-model="standardInfo.standardStatusVal" placeholder="请选择" clearable :disabled="props.projectId != ''">
										<el-option v-for="item in standardStatus.options" :key="item.id" :label="item.name" :value="item.id" />
									</el-select>
								</el-form-item>
							</el-col>
							<el-col :span="8">
								<el-form-item label="编制状态">
									<el-select v-model="standardInfo.compileStatusVal" placeholder="请选择" clearable :disabled="props.projectId != ''">
										<el-option v-for="item in compileStatus.options" :key="item.id" :label="item.name" :value="item.id" />
									</el-select>
								</el-form-item>
							</el-col>
							<el-col :span="8">
								<el-form-item label="基础类别">
									<el-tree-select
										v-model="standardInfo.basicCategoriesVal"
										:data="basicCategoriesArray"
										highlight-current
										check-strictly
										:props="{
											value: 'id',
											label: 'standardName',
											children: 'children'
										}"
										clearable
										:disabled="props.isDisabled"
										@change="handleBasicChange"
									/>
								</el-form-item>
							</el-col>
						</el-row>
						<el-row>
							<el-col :span="8">
								<el-form-item label="专题分类">
									<el-tree-select
										v-model="standardInfo.specialCategoriesVal"
										:data="specialCategoriesArray"
										highlight-current
										:props="{
											value: 'id',
											label: 'standardName',
											children: 'children'
										}"
										multiple
										clearable
										:disabled="props.isDisabled"
										@change="handleSpecialChange"
									/>
								</el-form-item>
							</el-col>
							<el-col :span="8">
								<el-form-item label="工程专业分类">
									<el-select v-model="standardInfo.engineeringMajorVal" multiple placeholder="请选择" clearable :disabled="props.isDisabled">
										<el-option v-for="item in engineeringMajor.options" :key="item.id" :label="item.name" :value="item.id" />
									</el-select>
								</el-form-item>
							</el-col>
							<el-col :span="8">
								<el-form-item label="工程全生命周期分类">
									<el-select v-model="standardInfo.lifecycleCategoryVal" multiple placeholder="请选择" clearable :disabled="props.isDisabled">
										<el-option v-for="item in lifecycleCategory.options" :key="item.id" :label="item.name" :value="item.id" />
									</el-select>
								</el-form-item>
							</el-col>
						</el-row>
						<el-row>
							<el-col :span="8">
								<el-form-item label="管理条线分类">
									<el-select v-model="standardInfo.managementLineVal" multiple placeholder="请选择" clearable :disabled="props.isDisabled">
										<el-option v-for="item in managementLine.options" :key="item.id" :label="item.name" :value="item.id" />
									</el-select>
								</el-form-item>
							</el-col>
							<el-col :span="8">
								<el-form-item label="建筑类型分类">
									<el-select v-model="standardInfo.buildingTypeVal" multiple placeholder="请选择" clearable :disabled="props.isDisabled">
										<el-option v-for="item in buildingType.options" :key="item.id" :label="item.name" :value="item.id" />
									</el-select>
								</el-form-item>
							</el-col>
							<el-col :span="8">
								<el-form-item label="长三角区域标准分类">
									<el-select v-model="standardInfo.yangtzeRiverTagVal" multiple placeholder="请选择" clearable :disabled="props.isDisabled">
										<el-option v-for="item in yangtzeRiverTag.options" :key="item.id" :label="item.name" :value="item.id" />
									</el-select>
								</el-form-item>
							</el-col>
						</el-row>
						<el-row>
							<el-col :span="8">
								<el-form-item label="标准国际化领域标签">
									<el-select v-model="standardInfo.internationalFieldVal" multiple placeholder="请选择" clearable :disabled="props.isDisabled">
										<el-option v-for="item in internationalField.options" :key="item.id" :label="item.name" :value="item.id" />
									</el-select>
								</el-form-item>
							</el-col>
							<el-col :span="8">
								<el-form-item label="热门领域标签">
									<el-select v-model="standardInfo.hotFieldVal" multiple placeholder="请选择" clearable :disabled="props.isDisabled">
										<el-option v-for="item in hotField.options" :key="item.id" :label="item.name" :value="item.id" />
									</el-select>
								</el-form-item>
							</el-col>
						</el-row>
						<el-row>
							<el-col :span="24">
								<el-form-item label="标准附件" prop="fileRecordId">
									<el-input
										v-model="standardInfo.file.fileName"
										readonly
										autocomplete="off"
										placeholder="请上传"
										style="width: 50%; margin-right: 10px"
									>
									</el-input>
									<el-upload
										ref="uploadRef"
										:action="uploadApi"
										:headers="uploadHeaders"
										:data="uploadData"
										:show-file-list="false"
										:on-success="handleUploadFileSuccess"
										:on-error="handleUploadFileError"
										:before-upload="beforeUpload"
										:disabled="uploadLoading"
									>
										<el-button type="primary" :loading="uploadLoading" :disabled="props.projectId != ''">上传</el-button>
									</el-upload>
									<el-button v-if="standardInfo.fileRecordId" type="default" style="margin-left: 10px" @click="handleUploadFilePreview"
										>下载</el-button
									>
								</el-form-item>
							</el-col>
						</el-row>
					</el-form>
				</div>
			</el-tab-pane>
			<el-tab-pane label="主参编单位" name="tab2" :disabled="!systemId">
				<div class="box">
					<zhubian :system-id="systemId" :project-id="projectInfoId" :current-tab="activeName" :is-disabled="props.isDisabled" />
				</div>
			</el-tab-pane>
			<el-tab-pane label="主要起草人" name="tab3" :disabled="!systemId">
				<div class="box">
					<qicaoren :system-id="systemId" :project-id="projectInfoId" :current-tab="activeName" :is-disabled="props.isDisabled" />
				</div>
			</el-tab-pane>
			<el-tab-pane label="主要审查人" name="tab4" :disabled="!systemId">
				<div class="box">
					<shencharen :system-id="systemId" :project-id="projectInfoId" :current-tab="activeName" :is-disabled="props.isDisabled" />
				</div>
			</el-tab-pane>
			<el-tab-pane label="条文" name="tab5" :disabled="!systemId">
				<div class="box">
					<tiaowen :system-id="systemId" :current-tab="activeName" :is-disabled="props.isDisabled" />
				</div>
			</el-tab-pane>
			<el-tab-pane label="引用标准" name="tab6" :disabled="!systemId">
				<div class="box">
					<biaozhun :system-id="systemId" :current-tab="activeName" :is-disabled="props.isDisabled" />
				</div>
			</el-tab-pane>
			<el-tab-pane label="应用项目" name="tab7" :disabled="!systemId">
				<div class="box">
					<xiangmu :system-id="systemId" :current-tab="activeName" :is-disabled="props.isDisabled" />
				</div>
			</el-tab-pane>
		</el-tabs>
		<template #footer>
			<div v-if="!props.isDisabled" class="dialog-foot">
				<el-button v-if="activeName == 'tab1'" type="primary" @click="submitForm(standardInfoRef)">保存</el-button>
				<el-button v-if="activeName != 'tab1'" @click="prevStep">上一步</el-button>
				<el-button v-if="activeName != 'tab7' && systemId" @click="nextStep">下一步</el-button>
				<el-button @click="closeModal">关闭</el-button>
			</div>
		</template>
	</cmDialog>
</template>
<script lang="ts" setup>
import { categoryDetailApi, categorysaveOrSubmitApi } from '@/api/standard/maintenance'
import { filePreviewById } from '@/api/sys/upload'
import cmDialog from '@/components/cm-dialog/index.vue'
import { useDictionaryStore } from '@/store/modules/dictionary'
import { useUserStore } from '@/store/modules/user'
import type { FormInstance, TabPaneName, UploadRawFile } from 'element-plus'
import { ElMessage, ElMessageBox } from 'element-plus'
import { computed, reactive, ref, watch } from 'vue'
import biaozhun from './biaozhun.vue'
import qicaoren from './qicaoren.vue'
import {
	Category,
	Label,
	Option,
	basicCategories,
	buildingType,
	compileStatus,
	engineeringMajor,
	hotField,
	internationalField,
	lifecycleCategory,
	managementLine,
	mandatoryCategory,
	specialCategories,
	standardCategory,
	standardStatus,
	yangtzeRiverTag
} from './selectors'
import shencharen from './shencharen.vue'
import tiaowen from './tiaowen.vue'
import xiangmu from './xiangmu.vue'
import zhubian from './zhubian.vue'

const userStore = useUserStore()

const dictionaryStore = useDictionaryStore()

const props = defineProps({
	modelValue: Boolean,
	editId: {
		type: String,
		default: ''
	},
	projectId: {
		type: String,
		default: ''
	},
	isDisabled: {
		type: Boolean,
		default: false
	}
})

const emit = defineEmits(['update:modelValue', 'submit-success', 'dialog-cancel'])

const dialogState = computed({
	get: () => props.modelValue,
	set: val => emit('update:modelValue', val)
})
const activeName = ref('tab1')
const standardInfoRef = ref<FormInstance>()
const standardInfo = ref({
	standardName: '',
	standardEnName: '',
	standardNumber: '',
	recordNumber: '',
	substitutedName: '',
	substitutedNo: '',
	seqNo: '',
	version: 1,
	initiateTime: '',
	publishTime: '',
	implementTime: '',
	abolishTime: '',
	approvalTime: '',
	remark: '',
	mandatoryCategoryVal: '', // 强制性分类
	standardCategoryVal: '', //标准类别
	standardStatusVal: '', //标准状态
	compileStatusVal: '', //编制状态
	basicCategoriesVal: '', //基础类别
	specialCategoriesVal: [], //专题分类
	engineeringMajorVal: [], //工程专业分类
	lifecycleCategoryVal: [], //工程全生命周期分类
	managementLineVal: [], //管理条线分类
	buildingTypeVal: [], //建筑类型分类
	yangtzeRiverTagVal: [], //长三角区域标准分类
	internationalFieldVal: [], //标准国际化领域标签
	hotFieldVal: [], //热门领域标签
	fileRecordId: '',
	file: {
		fileName: ''
	}
})
const isDataChanged = ref(false)

const standardInfoRules = reactive<any>({
	standardName: [
		{
			required: true,
			message: '请输入标准名称',
			trigger: 'blur'
		}
	],
	standardEnName: [
		{
			pattern: /^[A-Za-z0-9_\-\.@#$%&*+=~!^(){}[\]|\\;:'",<>/?]*$/,
			message: '只能输入英文、数字和符号',
			trigger: 'blur'
		}
	],
	fileRecordId: [{ required: true, message: '请上传文件', trigger: 'change' }]
})
const standardInfoRules1 = reactive<any>({
	standardName: [
		{
			required: true,
			message: '请输入标准名称',
			trigger: 'blur'
		}
	],
	standardEnName: [
		{
			pattern: /^[A-Za-z0-9_\-\.@#$%&*+=~!^(){}[\]|\\;:'",<>/?]*$/,
			message: '只能输入英文、数字和符号',
			trigger: 'blur'
		}
	]
})
const systemId = ref('')
const projectInfoId = ref('')
const nodeMap = new Map()

const basicCategoriesArray = ref([])
const specialCategoriesArray = ref([])

const uploadApi = `${import.meta.env.MODE === 'development' ? 'http://220.196.89.86:9173' : window.location.protocol + '//' + window.location.host}/JGBStandardWebApi/api/files/upload`
const uploadHeaders = {
	Authorization: userStore.token
}
const uploadData = {
	extCode: 'other',
	remark: '标准附件'
}
const uploadLoading = ref(false)

const isSaved = ref(false)

function buildNodeMap(nodes) {
	for (const node of nodes) {
		nodeMap.set(node.id, node)
		if (node.children) {
			buildNodeMap(node.children)
		}
	}
}

watch(
	() => dialogState.value,
	async val => {
		if (val) {
			resetInfo()
			activeName.value = 'tab1'
			isSaved.value = false
			if (props.projectId) {
				standardInfo.value.standardStatusVal = '6'
			}
			if (props.editId || props.projectId) {
				await getInfo()
			} else {
				basicCategoriesArray.value = JSON.parse(JSON.stringify(basicCategories.value))
				specialCategoriesArray.value = JSON.parse(JSON.stringify(specialCategories.value))
			}
			// buildNodeMap(specialCategories.value)
			if (props.projectId) {
				standardInfo.value.standardStatusVal = '6'
			}
			standardInfoRef.value?.validate()
		}
	}
)

watch(
	standardInfo,
	() => {
		isDataChanged.value = true // 标记为已修改
	}, // 防抖延迟 500ms
	{ deep: true } // 深度监听
)

const resetInfo = () => {
	systemId.value = ''
	projectInfoId.value = ''
	standardInfo.value = {
		standardName: '',
		standardEnName: '',
		standardNumber: '',
		recordNumber: '',
		substitutedName: '',
		substitutedNo: '',
		seqNo: '',
		version: 1,
		initiateTime: '',
		publishTime: '',
		implementTime: '',
		abolishTime: '',
		approvalTime: '',
		remark: '',
		mandatoryCategoryVal: '',
		standardCategoryVal: '',
		standardStatusVal: '',
		compileStatusVal: '',
		basicCategoriesVal: '',
		specialCategoriesVal: [],
		engineeringMajorVal: [],
		lifecycleCategoryVal: [],
		managementLineVal: [],
		buildingTypeVal: [],
		yangtzeRiverTagVal: [],
		internationalFieldVal: [],
		hotFieldVal: [],
		fileRecordId: '',
		file: {
			fileName: ''
		}
	}
}
const resetInfo2 = () => {
	standardInfo.value = {
		standardName: '',
		standardEnName: '',
		standardNumber: '',
		recordNumber: '',
		substitutedName: '',
		substitutedNo: '',
		seqNo: '',
		version: 1,
		initiateTime: '',
		publishTime: '',
		implementTime: '',
		abolishTime: '',
		approvalTime: '',
		remark: '',
		mandatoryCategoryVal: '',
		standardCategoryVal: '',
		standardStatusVal: '',
		compileStatusVal: '',
		basicCategoriesVal: '',
		specialCategoriesVal: [],
		engineeringMajorVal: [],
		lifecycleCategoryVal: [],
		managementLineVal: [],
		buildingTypeVal: [],
		yangtzeRiverTagVal: [],
		internationalFieldVal: [],
		hotFieldVal: [],
		fileRecordId: '',
		file: {
			fileName: ''
		}
	}
}

const handleBasicChange = () => {
	setHasChosen([standardInfo.value.basicCategoriesVal], basicCategoriesArray.value)
}

const handleSpecialChange = () => {
	setHasChosen(standardInfo.value.specialCategoriesVal, specialCategoriesArray.value)
}

// 更新所有节点的 hasChosen 状态
const setHasChosen = (ids: string[], nodes: any) => {
	resetHasChosen(nodes)
	if (ids.length > 0) {
		ids.forEach(id => {
			const node = findNodeById(nodes, id)
			if (node) {
				node.hasChosen = true
			}
		})
	}
}

// 递归重置所有节点的 hasChosen 为 false
const resetHasChosen = nodes => {
	nodes.forEach(node => {
		node.hasChosen = false
		if (node.children.length > 0) {
			resetHasChosen(node.children)
		}
	})
}

// 递归查找指定 ID 的节点
const findNodeById = (nodes, targetId) => {
	for (const node of nodes) {
		if (node.id === targetId) {
			return node
		}
		if (node.children.length > 0) {
			const found = findNodeById(node.children, targetId)
			if (found) {
				return found
			}
		}
	}
	return null
}

const collectSelectedId = (nodes: any[]) => {
	nodes.forEach(node => {
		if (node.hasChosen) {
			standardInfo.value.basicCategoriesVal = node.id
		}
		if (node.children.length > 0) {
			collectSelectedId(node.children)
		}
	})
}

// 递归查找选中节点id
const collectSelectedIds = (nodes: any[]) => {
	nodes.forEach(node => {
		if (node.hasChosen) {
			standardInfo.value.specialCategoriesVal.push(node.id)
		}
		if (node.children.length > 0) {
			collectSelectedIds(node.children)
		}
	})
}

const closeModal = () => {
	emit('update:modelValue', false)
}

const filterOptions = (items: Option[], targetIds: string | string[]): Option[] => {
	if (Array.isArray(targetIds)) {
		return items.filter(item => targetIds.includes(item.id))
	}
	return items.filter(item => item.id === targetIds)
}

const buildLabelEntry = (category: Label, targetVal: string | string[]) => {
	const options = filterOptions(category.options, targetVal)
	return {
		type: category.type,
		typeName: category.typeName,
		options
	}
}

const processCategory = (items: Category[], targetId: string | string[]) => {
	if (!targetId || (Array.isArray(targetId) && targetId.length === 0)) {
		return []
	}
	return items
		.filter(item => (Array.isArray(targetId) ? targetId.includes(item.id) : item.id === targetId))
		.map(({ id, pid, standardType }) => ({ id, pid, standardType }))
}

const submitForm = async (formEl: FormInstance | undefined) => {
	if (!formEl) {
		return
	}
	await formEl.validate((valid, fields) => {
		if (valid) {
			let labelsArr = []
			let basicCateArr = []
			let specialCateArr = []
			if (standardInfo.value.mandatoryCategoryVal) {
				labelsArr.push(buildLabelEntry(mandatoryCategory.value, standardInfo.value.mandatoryCategoryVal))
			}
			if (standardInfo.value.standardCategoryVal) {
				labelsArr.push(buildLabelEntry(standardCategory.value, standardInfo.value.standardCategoryVal))
			}
			if (standardInfo.value.standardStatusVal) {
				labelsArr.push(buildLabelEntry(standardStatus.value, standardInfo.value.standardStatusVal))
			}
			if (standardInfo.value.compileStatusVal) {
				labelsArr.push(buildLabelEntry(compileStatus.value, standardInfo.value.compileStatusVal))
			}

			if (standardInfo.value.engineeringMajorVal.length > 0) {
				labelsArr.push(buildLabelEntry(engineeringMajor.value, standardInfo.value.engineeringMajorVal))
			}
			if (standardInfo.value.lifecycleCategoryVal.length > 0) {
				labelsArr.push(buildLabelEntry(lifecycleCategory.value, standardInfo.value.lifecycleCategoryVal))
			}
			if (standardInfo.value.managementLineVal.length > 0) {
				labelsArr.push(buildLabelEntry(managementLine.value, standardInfo.value.managementLineVal))
			}
			if (standardInfo.value.buildingTypeVal.length > 0) {
				labelsArr.push(buildLabelEntry(buildingType.value, standardInfo.value.buildingTypeVal))
			}
			if (standardInfo.value.yangtzeRiverTagVal.length > 0) {
				labelsArr.push(buildLabelEntry(yangtzeRiverTag.value, standardInfo.value.yangtzeRiverTagVal))
			}
			if (standardInfo.value.internationalFieldVal.length > 0) {
				labelsArr.push(buildLabelEntry(internationalField.value, standardInfo.value.internationalFieldVal))
			}
			if (standardInfo.value.hotFieldVal.length > 0) {
				labelsArr.push(buildLabelEntry(hotField.value, standardInfo.value.hotFieldVal))
			}
			categorysaveOrSubmitApi({
				id: systemId.value,
				standardName: standardInfo.value.standardName,
				standardEnName: standardInfo.value.standardEnName,
				standardNumber: standardInfo.value.standardNumber,
				recordNumber: standardInfo.value.recordNumber,
				substitutedName: standardInfo.value.substitutedName,
				substitutedNo: standardInfo.value.substitutedNo,
				seqNo: standardInfo.value.seqNo,
				version: standardInfo.value.version,
				initiateTime: standardInfo.value.initiateTime,
				publishTime: standardInfo.value.publishTime,
				implementTime: standardInfo.value.implementTime,
				abolishTime: standardInfo.value.abolishTime,
				approvalTime: standardInfo.value.approvalTime,
				remark: standardInfo.value.remark,
				labels: labelsArr,
				basicCategories: basicCategoriesArray.value,
				specialCategories: specialCategoriesArray.value,
				projectInfoId: props.projectId,
				fileRecordId: standardInfo.value.fileRecordId
			}).then(res => {
				systemId.value = res.data.id
				isSaved.value = true
				ElMessage.success({
					message: '操作成功',
					duration: 500
				})
				isDataChanged.value = false
				emit('submit-success', res.data)
			})
		}
	})
}

const beforeTabLeave = (activeName: TabPaneName, oldActiveName: TabPaneName) => {
	const tabPromise = new Promise((resolve, reject) => {
		if (oldActiveName === 'tab1' && isDataChanged.value) {
			ElMessageBox.confirm('数据已修改，是否保存后再继续?', '提示', {
				confirmButtonText: '保存',
				cancelButtonText: '不保存',
				type: 'warning',
				showClose: false
			})
				.then(() => {
					isDataChanged.value = false
					resolve(true)
					submitForm(standardInfoRef.value)
				})
				.catch(() => {
					isDataChanged.value = false
					resolve(true)
				})
		} else {
			resolve(true)
		}
	})
	return tabPromise
}

const nextStep = () => {
	if (activeName.value === 'tab1' && isDataChanged.value) {
		ElMessageBox.confirm('数据已修改，是否保存后再继续?', '提示', {
			confirmButtonText: '保存',
			cancelButtonText: '不保存',
			type: 'warning',
			showClose: false
		})
			.then(() => {
				activeName.value = 'tab2'
				isDataChanged.value = false
				submitForm(standardInfoRef.value)
			})
			.catch(() => {
				activeName.value = 'tab2'
				isDataChanged.value = false
			})
	} else {
		const step = parseInt(activeName.value.substring(3))
		activeName.value = `tab${step + 1}`
	}
}
const prevStep = () => {
	const step = parseInt(activeName.value.substring(3))
	activeName.value = `tab${step - 1}`
	if (activeName.value === 'tab1') {
		resetInfo2()
		getInfo()
	}
}

const handleTabClick = (tab: TabPaneName) => {
	if (activeName.value === 'tab1') {
		resetInfo2()
		getInfo()
	}
}

const extractCategoryValue = (labels: Label[], type: string, isArray: boolean = false) => {
	const category = labels.find(item => item.type === type)
	if (!category) {
		return isArray ? [] : undefined
	}
	return isArray ? category.options.map(item => item.id) : category.options.map(item => item.id)[0]
}

const getInfo = async () => {
	let id = ''
	if (props.editId) {
		id = props.editId
	}
	if (systemId.value) {
		id = systemId.value
	}
	await categoryDetailApi({
		systemId: id,
		projectInfoId: props.projectId
	})
		.then(res => {
			standardInfo.value.standardName = res.data.standardName
			standardInfo.value.standardEnName = res.data.standardEnName
			standardInfo.value.standardNumber = res.data.standardNumber
			standardInfo.value.recordNumber = res.data.recordNumber
			standardInfo.value.substitutedName = res.data.substitutedName
			standardInfo.value.substitutedNo = res.data.substitutedNo
			standardInfo.value.seqNo = res.data.seqNo
			standardInfo.value.version = res.data.version
			standardInfo.value.initiateTime = res.data.initiateTime
			standardInfo.value.publishTime = res.data.publishTime
			standardInfo.value.implementTime = res.data.implementTime
			standardInfo.value.abolishTime = res.data.abolishTime
			standardInfo.value.approvalTime = res.data.approvalTime
			standardInfo.value.remark = res.data.remark
			systemId.value = res.data.id
			projectInfoId.value = res.data.projectInfoId
			const labels = res.data.labels
			const {
				mandatoryCategoryVal,
				standardCategoryVal,
				standardStatusVal,
				compileStatusVal,
				engineeringMajorVal,
				lifecycleCategoryVal,
				managementLineVal,
				buildingTypeVal,
				yangtzeRiverTagVal,
				internationalFieldVal,
				hotFieldVal
			} = {
				mandatoryCategoryVal: extractCategoryValue(labels, '4'),
				standardCategoryVal: extractCategoryValue(labels, '1'),
				standardStatusVal: extractCategoryValue(labels, '2'),
				compileStatusVal: extractCategoryValue(labels, '3'),
				engineeringMajorVal: extractCategoryValue(labels, '7', true),
				lifecycleCategoryVal: extractCategoryValue(labels, '5', true),
				managementLineVal: extractCategoryValue(labels, '8', true),
				buildingTypeVal: extractCategoryValue(labels, '6', true),
				yangtzeRiverTagVal: extractCategoryValue(labels, '14', true),
				internationalFieldVal: extractCategoryValue(labels, '12', true),
				hotFieldVal: extractCategoryValue(labels, '13', true)
			}

			// 统一赋值
			Object.assign(standardInfo.value, {
				mandatoryCategoryVal,
				standardCategoryVal,
				standardStatusVal,
				compileStatusVal,
				engineeringMajorVal,
				lifecycleCategoryVal,
				managementLineVal,
				buildingTypeVal,
				yangtzeRiverTagVal,
				internationalFieldVal,
				hotFieldVal
			})
			basicCategoriesArray.value = res.data.basicCategories
			specialCategoriesArray.value = res.data.specialCategories
			collectSelectedId(basicCategoriesArray.value)
			collectSelectedIds(specialCategoriesArray.value)
			if (res.data.fileRecordId) {
				standardInfo.value.fileRecordId = res.data.fileRecordId
				standardInfo.value.file = res.data.file
			} else {
				standardInfo.value.fileRecordId = ''

				standardInfo.value.file = {
					fileName: ''
				}
			}
			setTimeout(() => {
				isDataChanged.value = false
			}, 100)
		})
		.catch(() => {})
}

const handleUploadFileSuccess = (res: any, uploadFile: UploadRawFile) => {
	uploadLoading.value = false
	if (res.code == '200') {
		standardInfo.value.file.fileName = res.data.fileRealName + '.' + res.data.fileExtName
		standardInfo.value.fileRecordId = res.data.id
	}
}

const handleUploadFileError = (error: Error, uploadFile: UploadRawFile) => {
	ElMessage.error(error.message)
}

const beforeUpload = (file: File) => {
	uploadLoading.value = true
}

const handleUploadFilePreview = (ruploadFile: any) => {
	if (standardInfo.value.fileRecordId) {
		filePreviewById(standardInfo.value.fileRecordId).then(res => {
			window.open(res.data.url)
		})
	}
}
</script>
<style lang="scss" scoped>
.box :deep(.el-form-item__label) {
	font-size: 14px !important;
}
.tabs :deep(.el-tabs__nav-wrap) {
	display: flex;
	justify-content: center;
	margin-top: 10px;
}

.box {
	border: solid 1px #eee;
	padding: 20px;
}

.dialog-foot {
	display: flex;
	justify-content: center;
	margin-bottom: 10px;
	padding-bottom: 20px;
}
</style>
